package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.chlid

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.BaseQuickAdapter
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.networking.RestClient
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.bean.AreaItemBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.AGENCY_APPLYING_AREA_Event
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.CITY
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.DISTRICT
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.PROVINCE
import com.example.shushiyunsst.util.HiDataBus
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import com.example.wallet.utils.Preference
import com.google.android.material.tabs.TabLayout
import ikidou.reflect.TypeBuilder
import java.lang.reflect.Type
import java.math.BigDecimal

class AgencyApplyingAreaFragment : SimpleListFragment<AreaItemBean>() {

    companion object {


        fun newInstance(): AgencyApplyingAreaFragment {
            val args = Bundle()
            val fragment = AgencyApplyingAreaFragment()
            fragment.arguments = args
            return fragment
        }
    }

    var mTab: TabLayout.Tab? = null

    var selectedItem: AreaItemBean? = null

    var isHaveSelected = false

    private val icon = AppGlobals.getApplication().getString(R.string.wallet_sst)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
        isAddDividerItemDecoration = false
        isEnableLoadMore = false
        isInitialRefresh = false
        isAlwaysRefresh = false
    }


    private var sstBalance: BigDecimal = BigDecimal.valueOf(0)

    override fun getItemLayout(): Int {
        return R.layout.fragment_agency_applying_area
    }

    override fun initView(view: View) {
        super.initView(view)

        mRecyclerView.overScrollMode = View.OVER_SCROLL_NEVER

        content_frame.removeAllViews()
        addContentFrame(R.layout.fragment_agency_applying_content_frame_area)

    }

    override fun convertItem(helper: JssBaseViewHolder?, item: AreaItemBean?) {

        item?.areaType = Integer.valueOf(mTab?.tag.toString())

        isHaveSelected = item?.aid == selectedItem?.aid

        helper?.setText(R.id.title, "${item?.areaName}")
            ?.setText(R.id.mAgency, "代理人：${item?.realName}")
            ?.setText(R.id.mFee, "代理费：${item?.proxyFee} $icon")
            ?.setViewSelect(R.id.selected, isHaveSelected)
    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(AreaItemBean::class.java).endSubType().build()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        super.onItemClick(adapter, view, position)

        val item = mAdapter.getItem(position)

        item.sstBalance = sstBalance

        if (selectedItem?.areaType == item.areaType) {

            item.parentArea = selectedItem?.parentArea

        } else {
            item.parentArea = selectedItem
        }

        selectedItem = item

        mAdapter.notifyDataSetChanged()

        HiDataBus.with<AreaItemBean>(AGENCY_APPLYING_AREA_Event).postStickyData(item)

    }

    override fun onRefresh() {
        content_frame.visibility = View.VISIBLE
        super.onRefresh()
    }

    override fun netRequest() {
        when (mTab?.tag) {
            PROVINCE -> {
                if (selectedItem?.areaType != PROVINCE) {
                    selectedItem = getArea(PROVINCE, selectedItem)
                }
                getProvince()
            }

            CITY -> {
                if (selectedItem?.areaType != CITY
                ) {
                    selectedItem = getArea(CITY, selectedItem)
                }

                getCity()
            }

            DISTRICT -> {
                if (selectedItem?.areaType != DISTRICT
                ) {
                    selectedItem = getArea(DISTRICT, selectedItem)
                }
                getDistrict()
            }
        }
    }

    private fun getArea(areaType: Int?, currentArea: AreaItemBean?): AreaItemBean? {

        var areaItemBean: AreaItemBean? = null

        val parentArea = currentArea?.parentArea

        if (parentArea != null) {
            areaItemBean = if (parentArea.areaType == areaType) {
                parentArea
            } else {
                getArea(areaType, parentArea)
            }
        }
        return if (areaItemBean?.areaType == areaType) areaItemBean else currentArea
//        return areaItemBean ?: currentArea
    }

    private fun getDistrict() {
//        Log.d("parentArea", "getDistrict: ${selectedItem?.parentArea?.areaName}")
//        val paid = selectedItem?.parentArea?.aid ?: selectedItem?.aid
//        val paid = selectedItem?.aid

        val paid = if (selectedItem?.areaType == DISTRICT)
            selectedItem?.parentArea?.aid
        else
            selectedItem?.aid

        RestClient.builder()
            .url(R.string.queryAreaListByParams)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "areaType" to "${mTab?.tag}",
                        "paid" to "$paid"
                    )
                )
            )
            .success { parseDate(it) }
            .failure {
                onFailed()
            }
            .error { _, _ ->
                onFailed()
            }.build().post()
    }

    private fun getCity() {
        val paid = if (selectedItem?.areaType == CITY)
            selectedItem?.parentArea?.aid
        else
            selectedItem?.aid

//        val paid = selectedItem?.parentArea?.aid ?: selectedItem?.aid

        RestClient.builder()
            .url(R.string.queryAreaListByParams)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "areaType" to "${mTab?.tag}",
                        "paid" to "$paid"
                    )
                )
            )
            .success { parseDate(it) }
            .failure {
                onFailed()
            }
            .error { _, _ ->
                onFailed()
            }.build().post()
    }

    private fun getProvince() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val deviceTokens = Preference.HOLDER.getCustomAppProfile(CURRENT_DEVICE_TOKEN)
        RestClient.builder()
            .url(R.string.applyProxyPre)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "deviceToken" to "$deviceTokens",
                        "uid" to "${userInfo?.uid}"
                    )
                )
            )
            .success {
                Log.d("lazyInit", "lazyInit: $it")
                parseDate(it)
            }.failure { onFailed() }
            .error { _, _ -> onFailed() }
            .build().post()
    }

    override fun parseDate(data: String?) {
//        super.parseDate(data)

        when (mTab?.tag) {
            PROVINCE -> parseDateProvince(data)

            CITY -> parseDateCity(data)

            DISTRICT -> parseDateDistrict(data)
        }
        content_frame.visibility = View.GONE
    }

    override fun onFailed() {
        super.onFailed()
        content_frame.visibility = View.GONE
    }

    private fun parseDateProvince(data: String?) {
        val obj = JSON.parseObject(data)
        val proList = obj["proList"] ?: ""
        sstBalance = obj.getBigDecimal("sstBalance")
        val array = JSON.parseArray(JSON.toJSONString(proList), AreaItemBean::class.java)
        loadListDate(array)
    }

    private fun parseDateCity(data: String?) {
        val obj = JSON.parseObject(data)
        val proList = obj["proList"] ?: ""
        val array = JSON.parseArray(JSON.toJSONString(proList), AreaItemBean::class.java)
        loadListDate(array)
    }

    private fun parseDateDistrict(data: String?) {
        val obj = JSON.parseObject(data)
        val proList = obj["proList"] ?: ""
        val array = JSON.parseArray(JSON.toJSONString(proList), AreaItemBean::class.java)
        loadListDate(array)
    }


    override fun preEmptyView() {
        val textView: TextView? = list_empty_view.findViewById(R.id.textView)
        textView?.text = "暂无该区域可申请的代理"
    }

}